<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="490px" :title="`${drawerProps.title}照护项目`">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="任务分类" prop="categorizeId">
        <el-select v-model="drawerProps.row!.categorizeId" placeholder="请选择任务分类" style="width: 240px">
          <el-option v-for="item in categorizeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-button type="primary" @click="loadCategorizeList" icon="Refresh" style="width: 80px; margin-left: 10px">
          刷新
        </el-button>
      </el-form-item>

      <el-form-item label="任务名称" prop="name">
        <el-input v-model="drawerProps.row!.name" placeholder="请输入任务名称" />
      </el-form-item>

      <el-form-item label="是否每日任务" prop="isDailyMission">
        <el-radio-group v-model="drawerProps.row!.isDailyMission">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="drawerProps.row!.isDailyMission === 1">
        <el-form-item label="建议开始时间">
          <el-time-select
            v-model="drawerProps.row!.dailyMissionStartTime"
            placeholder="选择开始时间"
            start="00:00"
            step="00:10"
            end="23:50"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="建议结束时间">
          <el-time-select
            v-model="drawerProps.row!.dailyMissionEndTime"
            placeholder="选择结束时间"
            :min-time="drawerProps.row!.dailyMissionStartTime"
            start="00:00"
            step="00:10"
            end="23:50"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="建议执行次数">
          <el-input
            v-model="drawerProps.row!.dailyMissionExecutionCount"
            placeholder="建议执行次数"
            :prefix-icon="Mouse"
            style="width: 240px"
          />
          <span style="margin-left: 10px; font-size: 16px">次</span>
        </el-form-item>
      </template>

      <el-form-item label="注意事项" prop="description">
        <el-input v-model="drawerProps.row!.description" type="textarea" placeholder="请输入注意事项" :rows="4" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="drawerVisible = false" icon="Close">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit" icon="Select">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { CareMission } from "@/api/interface";
import { getCareMissionCategorizeList } from "@/api/modules/care-mission-categorize";
import { saveCareMission } from "@/api/modules/care-mission";
import { Mouse } from "@element-plus/icons-vue";

// 组件挂载时加载任务分类列表
onMounted(() => {
  loadCategorizeList();
});

// 表单验证规则
const rules = reactive({
  categorizeId: [{ required: true, message: "请选择任务分类", trigger: "blur" }],
  name: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  isDailyMission: [{ required: true, message: "请选择是否每日任务", trigger: "change" }]
});

// 抽屉组件参数接口
interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<CareMission.ResCareMission>;
  getTableList?: () => void;
}

// 加载任务分类列表
const categorizeList = ref<CareMission.ResCareMissionCategorize[]>([]);
const loadCategorizeList = async () => {
  const params: CareMission.ReqCareMissionCategorizeListParams = {
    includeMissions: false,
    selectPlatform: false
  };
  const res = await getCareMissionCategorizeList(params);
  categorizeList.value = res.data || [];
};

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {} as Partial<CareMission.ResCareMission>
});

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  if (drawerProps.value.title === "添加") {
    // 新增任务时，没有id，默认设置为undefined
    drawerProps.value.row.id = undefined;
    // 新增任务时，默认设置为非每日任务
    drawerProps.value.row.isDailyMission = 1;
    // 新增任务时，建议时段默认设置为undefined
    drawerProps.value.row.dailyMissionStartTime = undefined;
    drawerProps.value.row.dailyMissionEndTime = undefined;
    // 新增任务时，没有分类，分类设置为undefined
    if (params.row.categorizeId === 0 && categorizeList.value.length > 0) {
      drawerProps.value.row!.categorizeId = categorizeList.value[0].id;
    }
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      ElMessage.success({ message: `${drawerProps.value.title}任务成功！` });
      if (drawerProps.value.row.isDailyMission === 0) {
        drawerProps.value.row.dailyMissionStartTime = undefined;
        drawerProps.value.row.dailyMissionEndTime = undefined;
        drawerProps.value.row.dailyMissionExecutionCount = undefined;
      }
      await saveCareMission(drawerProps.value.row as CareMission.ReqCareMissionSaveParams);
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

// 暴露方法给父组件调用
defineExpose({
  // 接收父组件传过来的参数
  acceptParams
});
</script>

<style scoped lang="scss">
// 样式可以根据需要调整
</style>
